package com.skivingcloud.admin.sys.controller;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.skivingcloud.admin.constants.Constant;
import com.skivingcloud.admin.security.UserUtil;
import com.skivingcloud.admin.sys.entity.SysMenu;
import com.skivingcloud.admin.sys.entity.SysTenant;
import com.skivingcloud.admin.sys.entity.SysTenantMenu;
import com.skivingcloud.admin.sys.service.SysMenuService;
import com.skivingcloud.admin.sys.service.SysTenantMenuService;
import com.skivingcloud.admin.sys.service.SysTenantService;
import com.skivingcloud.common.utils.PageParameter;
import com.skivingcloud.common.utils.ReturnT;
import com.skivingcloud.common.utils.UuidUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  控制层。
 *
 * @author skivingcloud
 * @since 2023-08-28
 */
@Tag(name = "SysTenantController", description = "租户管理API")
@RestController
@RequestMapping("/sysTenant/")
public class SysTenantController {
    private static final Logger log = LoggerFactory.getLogger(SysTenantController.class);
    @Resource
    private SysTenantService sysTenantService;
    @Resource
    private SysTenantMenuService sysTenantMenuService;
    @Resource
    private SysMenuService sysMenuService;
    /**
     * 添加。
     *
     * @param sysTenant 租户
     * @return {@code 0} 添加成功，{@code 500} 添加失败
     */
    @Operation(summary = "新增租户", description = "新增租户")
    @ApiResponse(responseCode = "2xx",description = "新增租户")
    @PostMapping("save")
    @CacheEvict(value="skivingTenant", allEntries = true)
    public ReturnT<Boolean> save(@Validated @RequestBody SysTenant sysTenant) {
        try{
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SysTenant::getTenantCode).eq(sysTenant.getTenantCode());
            boolean exists = sysTenantService.exists(queryWrapper);
            if(exists){
                return ReturnT.error("租户编号重复！");
            }
            sysTenant.setId(UuidUtil.get32UUID());
            sysTenant.setCreater(UserUtil.getCurrentUser().getId());
            sysTenant.setCreateTime(LocalDateTime.now());
            return ReturnT.ok(sysTenantService.save(sysTenant));
        }catch(Exception e){
            log.error("保存租户失败", e);
            return ReturnT.error("保存租户失败！");
        }
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code 0} 删除成功，{@code 500} 删除失败
     */
    @Operation(summary = "删除租户", description = "删除租户")
    @ApiResponse(responseCode = "2xx",description = "删除租户")
    @GetMapping("remove/{id}")
    @CacheEvict(value="skivingTenant", allEntries = true)
    public ReturnT<Boolean> remove(@PathVariable(name="id") Serializable id) {
        try{
            if(Constant.SUPER_ADMIN_TENANT_ID.equals(id)) {
                return ReturnT.error("超级管理员租户为内置租户，请勿删除！");
            }
            return ReturnT.ok(sysTenantService.removeById(id));
        }catch(Exception e){
            log.error("删除租户失败", e);
            return ReturnT.error("删除租户失败！");
        }
    }

    /**
     * 根据主键更新。
     *
     * @param sysTenant 租户
     * @return {@code 0} 更新成功，{@code 500} 更新失败
     */
    @Operation(summary = "修改租户", description = "修改租户")
    @ApiResponse(responseCode = "2xx",description = "修改租户")
    @PostMapping("update")
    @CacheEvict(value="skivingTenant", allEntries = true)
    public ReturnT<Boolean> update(@Validated @RequestBody SysTenant sysTenant) {
        try{
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SysTenant::getTenantCode).eq(sysTenant.getTenantCode())
                    .and(SysTenant::getId).ne(sysTenant.getId());
            boolean exists = sysTenantService.exists(queryWrapper);
            if(exists){
                return ReturnT.error("租户编号重复！");
            }
            sysTenant.setModUser(UserUtil.getCurrentUser().getId());
            sysTenant.setModTime(LocalDateTime.now());
            return ReturnT.ok(sysTenantService.updateById(sysTenant));
        }catch(Exception e){
            log.error("保存租户失败", e);
            return ReturnT.error("保存租户失败！");
        }
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @Operation(summary = "根据主键获取租户", description = "根据主键获取租户")
    @ApiResponse(responseCode = "2xx",description = "根据主键获取租户")
    @GetMapping("getInfo/{id}")
    public ReturnT<SysTenant> getInfo(@PathVariable(name="id") Serializable id) {
        return ReturnT.ok(sysTenantService.getById(id));
    }

    /**
     * 分页查询。
     *
     * @param parameter 分页对象
     * @return 分页对象
     */
    @Operation(summary = "分页查询租户", description = "分页查询租户")
    @ApiResponse(responseCode = "2xx",description = "分页查询租户")
    @PostMapping("page")
    public ReturnT<Page<SysTenant>> page(@RequestBody PageParameter<SysTenant> parameter) {
        return ReturnT.ok(sysTenantService.queryByPage(parameter));
    }
    
    /**
     * 查询租户信息{key:'', value:''}
     *
     * @return 租户信息{key:'', value:''}
     */
    @Operation(summary = "查询租户信息", description = "查询租户信息")
    @ApiResponse(responseCode = "2xx",description = "查询租户信息")
    @GetMapping("getTenantSelect")
    public ReturnT<List<Map<String, Object>>> getTenantSelect() {
        List<Map<String, Object>> list = sysTenantService.getTenantSelect();
        return ReturnT.ok(list);
    }
    
    /**
     * 删除租户
     * @param ids 租户id
     * @return 删除结果
     */
    @Operation(summary = "删除租户", description = "租户",
            parameters = {@Parameter(name = "ids", description = "租户id")})
    @ApiResponse(responseCode = "2xx",description = "删除租户")
    @PostMapping("delete")
//    @PreAuthorize("hasAuthority('sys:tenant:delete')")
    public ReturnT<String> delete(@RequestBody String[] ids){
        try{
            if(Arrays.asList(ids).contains(Constant.SUPER_ADMIN_TENANT_ID)) {
                return ReturnT.error("超级管理员租户为内置租户，请勿删除！");
            }
            sysTenantService.deleteBatch(ids);
            return ReturnT.ok("删除租户成功");
        }catch(Exception e){
            log.error("删除租户失败", e);
            return ReturnT.error("删除租户失败");
        }
    }
    
    /**
     * 根据租户id加载资源树权限
     *
     * @param id 角色id
     * @return 资源权限
     */
    @GetMapping("getSysTenantResTree/{id}")
    @Operation(summary="根据租户id加载资源树")
    public ReturnT<Map<String, Object>> getSysTenantResTree(@PathVariable("id") String id){
        List<SysMenu> list = sysMenuService.getMenuList();
        List<SysTenantMenu> tenantRes;
        tenantRes = sysTenantMenuService.getResTreeByTenantId(id);
        Map<String, Object> res = new HashMap<>();
        res.put("tree", list);
        res.put("tenantRes", tenantRes);
        return ReturnT.ok(res);
    }
    
    /**
     * 设置租户资源范围
     *
     * @param tenant 租户
     * @return 结果
     */
    @PostMapping("setSysTenantMenu")
    @Operation(summary="设置租户资源范围")
    public ReturnT<String> setSysTenantMenu(@RequestBody SysTenant tenant) {
        try {
            sysTenantMenuService.setSysTenantMenu(tenant);
            return ReturnT.ok();
        } catch (Exception e) {
            log.error("设置资源权限失败", e);
            return ReturnT.error("设置资源权限失败");
        }
    }
}
